<template>
  <div class="app-container p-6">
    <!-- 页面标题 -->
    <div class="page-header-section mb-6">
      <div class="page-title-area">
        <h1 class="text-2xl font-bold text-text-primary">安全监控</h1>
        <p class="text-text-muted mt-2">实时监控系统安全状态、权限访问和异常行为检测</p>
      </div>
      <div class="page-actions-area mt-4 flex gap-2">
        <button
          @click="refreshData"
          :disabled="loading"
          class="primary-action-btn bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-sync mr-2" :class="{ 'animate-spin': loading }"></i>
          <span>刷新数据</span>
        </button>
        <button
          @click="toggleAutoRefresh"
          :class="autoRefresh ? 'bg-success hover:bg-success-hover' : 'bg-secondary hover:bg-secondary-hover'"
          class="text-white px-4 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-play mr-2" v-if="!autoRefresh"></i>
          <i class="fas fa-pause mr-2" v-else></i>
          <span>{{ autoRefresh ? '停止自动刷新' : '自动刷新' }}</span>
        </button>
        <button
          @click="exportSecurityReport"
          v-permission="'security:export'"
          class="bg-info hover:bg-info-hover text-white px-4 py-2 rounded-md flex items-center shadow-card transition-all"
        >
          <i class="fas fa-download mr-2"></i>
          <span>导出报告</span>
        </button>
      </div>
    </div>

    <!-- 安全指标卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">活跃会话</p>
            <p class="text-2xl font-bold text-text-primary">{{ formatNumber(securityStats?.activeSessions) }}</p>
            <p class="text-text-secondary text-sm">当前在线用户</p>
          </div>
          <div class="metric-icon bg-green-500/20 text-green-600 rounded-full p-3">
            <i class="fas fa-users text-xl"></i>
          </div>
        </div>
      </div>

      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">登录失败次数</p>
            <p class="text-2xl font-bold text-text-primary" :class="getFailedLoginsClass()">
              {{ formatNumber(securityStats?.failedLogins) }}
            </p>
            <p class="text-text-secondary text-sm">24小时内</p>
          </div>
          <div class="metric-icon bg-red-500/20 text-red-600 rounded-full p-3">
            <i class="fas fa-exclamation-triangle text-xl"></i>
          </div>
        </div>
      </div>

      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">权限检查</p>
            <p class="text-2xl font-bold text-text-primary">{{ formatNumber(securityStats?.permissionChecks) }}</p>
            <p class="text-text-secondary text-sm">今日总计</p>
          </div>
          <div class="metric-icon bg-blue-500/20 text-blue-600 rounded-full p-3">
            <i class="fas fa-shield-alt text-xl"></i>
          </div>
        </div>
      </div>

      <div class="metric-card bg-panel rounded-lg shadow-card p-6">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-text-muted text-sm">安全等级</p>
            <p class="text-2xl font-bold" :class="getSecurityLevelClass()">{{ securityStats?.securityLevel }}</p>
            <p class="text-text-secondary text-sm">系统安全状态</p>
          </div>
          <div class="metric-icon bg-yellow-500/20 text-yellow-600 rounded-full p-3">
            <i class="fas fa-lock text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 安全事件和威胁监控 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
      <!-- 最近安全事件 -->
      <div class="monitoring-panel bg-panel rounded-lg shadow-card">
        <div class="panel-header p-6 border-b border-border">
          <h3 class="text-lg font-semibold text-text-primary">最近安全事件</h3>
          <p class="text-text-muted text-sm">实时安全事件监控</p>
        </div>
        <div class="panel-content p-6">
          <div class="space-y-4" v-if="securityEvents?.length">
            <div 
              v-for="event in securityEvents" 
              :key="event.id"
              class="security-event-item p-4 bg-bg-soft rounded-lg border-l-4"
              :class="getEventTypeClass(event.type)"
            >
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <i :class="getEventIcon(event.type)" class="mr-3"></i>
                  <div>
                    <p class="font-semibold text-text-primary">{{ event.description }}</p>
                    <p class="text-sm text-text-muted">{{ event.source }} - {{ formatTime(event.timestamp) }}</p>
                  </div>
                </div>
                <div class="text-sm text-text-secondary">{{ event.severity }}</div>
              </div>
            </div>
          </div>
          <div v-else class="text-center text-text-muted py-8">
            <i class="fas fa-shield-check text-4xl mb-2"></i>
            <p>暂无安全事件</p>
          </div>
        </div>
      </div>

      <!-- IP访问统计 -->
      <div class="monitoring-panel bg-panel rounded-lg shadow-card">
        <div class="panel-header p-6 border-b border-border">
          <h3 class="text-lg font-semibold text-text-primary">IP访问统计</h3>
          <p class="text-text-muted text-sm">TOP访问IP和地理分布</p>
        </div>
        <div class="panel-content p-6">
          <div class="space-y-3" v-if="ipStats?.length">
            <div 
              v-for="ip in ipStats" 
              :key="ip.address"
              class="ip-stat-item flex items-center justify-between p-3 bg-bg-soft rounded-lg"
            >
              <div class="flex items-center">
                <div class="w-3 h-3 rounded-full mr-3" :class="getIpStatusClass(ip.status)"></div>
                <div>
                  <p class="font-mono text-text-primary">{{ ip.address }}</p>
                  <p class="text-sm text-text-muted">{{ ip.location }}</p>
                </div>
              </div>
              <div class="text-right">
                <p class="font-semibold text-text-primary">{{ formatNumber(ip.requests) }}</p>
                <p class="text-sm text-text-secondary">请求次数</p>
              </div>
            </div>
          </div>
          <div v-else class="text-center text-text-muted py-8">
            <i class="fas fa-globe text-4xl mb-2"></i>
            <p>暂无访问数据</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户权限监控 -->
    <div class="monitoring-panel bg-panel rounded-lg shadow-card mb-6">
      <div class="panel-header p-6 border-b border-border">
        <h3 class="text-lg font-semibold text-text-primary">权限访问监控</h3>
        <p class="text-text-muted text-sm">权限检查统计和异常访问检测</p>
      </div>
      <div class="panel-content p-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="permission-stat">
            <div class="stat-header flex items-center mb-3">
              <i class="fas fa-check-circle text-green-500 mr-2"></i>
              <span class="font-semibold text-text-primary">权限通过</span>
            </div>
            <div class="stat-value text-2xl font-bold text-green-600">
              {{ formatNumber(permissionStats?.allowed) }}
            </div>
            <div class="stat-change text-sm text-text-muted">
              比昨日 +{{ formatPercent(permissionStats?.allowedChange) }}
            </div>
          </div>

          <div class="permission-stat">
            <div class="stat-header flex items-center mb-3">
              <i class="fas fa-times-circle text-red-500 mr-2"></i>
              <span class="font-semibold text-text-primary">权限拒绝</span>
            </div>
            <div class="stat-value text-2xl font-bold text-red-600">
              {{ formatNumber(permissionStats?.denied) }}
            </div>
            <div class="stat-change text-sm text-text-muted">
              比昨日 {{ permissionStats?.deniedChange >= 0 ? '+' : '' }}{{ formatPercent(permissionStats?.deniedChange) }}
            </div>
          </div>

          <div class="permission-stat">
            <div class="stat-header flex items-center mb-3">
              <i class="fas fa-exclamation-circle text-yellow-500 mr-2"></i>
              <span class="font-semibold text-text-primary">异常访问</span>
            </div>
            <div class="stat-value text-2xl font-bold text-yellow-600">
              {{ formatNumber(permissionStats?.suspicious) }}
            </div>
            <div class="stat-change text-sm text-text-muted">
              需要关注
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// 定义接口
interface SecurityStats {
  activeSessions: number
  failedLogins: number
  permissionChecks: number
  securityLevel: string
}

interface SecurityEvent {
  id: string
  type: string
  description: string
  source: string
  timestamp: string
  severity: string
}

interface IpStat {
  address: string
  location: string
  requests: number
  status: string
}

interface PermissionStats {
  allowed: number
  denied: number
  suspicious: number
  allowedChange: number
  deniedChange: number
}

// 响应式数据
const loading = ref(false)
const autoRefresh = ref(false)
let refreshTimer: NodeJS.Timeout | null = null

const securityStats = ref<SecurityStats>({
  activeSessions: 0,
  failedLogins: 0,
  permissionChecks: 0,
  securityLevel: 'NORMAL'
})

const securityEvents = ref<SecurityEvent[]>([])
const ipStats = ref<IpStat[]>([])
const permissionStats = ref<PermissionStats>({
  allowed: 0,
  denied: 0,
  suspicious: 0,
  allowedChange: 0,
  deniedChange: 0
})

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchSecurityStats(),
      fetchSecurityEvents(),
      fetchIpStats(),
      fetchPermissionStats()
    ])
  } catch (error) {
    ElMessage.error('刷新数据失败')
    console.error('Error refreshing security data:', error)
  } finally {
    loading.value = false
  }
}

const fetchSecurityStats = async () => {
  // TODO: 实现API调用
  // 模拟数据
  securityStats.value = {
    activeSessions: Math.floor(Math.random() * 500) + 100,
    failedLogins: Math.floor(Math.random() * 50),
    permissionChecks: Math.floor(Math.random() * 10000) + 5000,
    securityLevel: ['NORMAL', 'WARNING', 'CRITICAL'][Math.floor(Math.random() * 3)]
  }
}

const fetchSecurityEvents = async () => {
  // TODO: 实现API调用
  // 模拟数据
  securityEvents.value = [
    {
      id: '1',
      type: 'login_failure',
      description: '用户登录失败',
      source: 'user@example.com',
      timestamp: new Date().toISOString(),
      severity: 'WARNING'
    },
    {
      id: '2',
      type: 'permission_denied',
      description: '权限访问被拒绝',
      source: 'admin@example.com',
      timestamp: new Date(Date.now() - 300000).toISOString(),
      severity: 'INFO'
    }
  ]
}

const fetchIpStats = async () => {
  // TODO: 实现API调用
  // 模拟数据
  ipStats.value = [
    { address: '192.168.1.100', location: '北京市', requests: 1250, status: 'normal' },
    { address: '10.0.0.50', location: '上海市', requests: 890, status: 'normal' },
    { address: '172.16.0.25', location: '深圳市', requests: 156, status: 'suspicious' }
  ]
}

const fetchPermissionStats = async () => {
  // TODO: 实现API调用
  // 模拟数据
  permissionStats.value = {
    allowed: Math.floor(Math.random() * 5000) + 2000,
    denied: Math.floor(Math.random() * 200) + 50,
    suspicious: Math.floor(Math.random() * 20) + 5,
    allowedChange: (Math.random() - 0.5) * 20,
    deniedChange: (Math.random() - 0.5) * 40
  }
}

const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  if (autoRefresh.value) {
    refreshTimer = setInterval(refreshData, 30000) // 30秒刷新一次
  } else if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

const exportSecurityReport = () => {
  ElMessage.success('安全报告导出功能待实现')
}

// 样式和状态方法
const getFailedLoginsClass = () => {
  const count = securityStats.value?.failedLogins || 0
  if (count > 100) return 'text-red-600'
  if (count > 50) return 'text-yellow-600'
  return 'text-green-600'
}

const getSecurityLevelClass = () => {
  const level = securityStats.value?.securityLevel
  switch (level) {
    case 'CRITICAL': return 'text-red-600'
    case 'WARNING': return 'text-yellow-600'
    case 'NORMAL': return 'text-green-600'
    default: return 'text-text-primary'
  }
}

const getEventTypeClass = (type: string) => {
  switch (type) {
    case 'login_failure': return 'border-red-500'
    case 'permission_denied': return 'border-yellow-500'
    case 'suspicious_activity': return 'border-red-500'
    default: return 'border-blue-500'
  }
}

const getEventIcon = (type: string) => {
  switch (type) {
    case 'login_failure': return 'fas fa-sign-in-alt text-red-500'
    case 'permission_denied': return 'fas fa-ban text-yellow-500'
    case 'suspicious_activity': return 'fas fa-exclamation-triangle text-red-500'
    default: return 'fas fa-info-circle text-blue-500'
  }
}

const getIpStatusClass = (status: string) => {
  switch (status) {
    case 'normal': return 'bg-green-500'
    case 'suspicious': return 'bg-yellow-500'
    case 'blocked': return 'bg-red-500'
    default: return 'bg-gray-500'
  }
}

// 格式化方法
const formatNumber = (num: number | undefined): string => {
  if (num === undefined) return '0'
  return num.toLocaleString()
}

const formatPercent = (num: number | undefined): string => {
  if (num === undefined) return '0%'
  return `${num.toFixed(1)}%`
}

const formatTime = (timestamp: string): string => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  refreshData()
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.app-container {
  min-height: calc(100vh - 200px);
}

.page-header-section {
  background: var(--el-bg-color);
}

.metric-card {
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.metric-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.monitoring-panel {
  transition: all 0.3s ease;
}

.security-event-item {
  transition: all 0.2s ease;
}

.security-event-item:hover {
  background: var(--el-color-info-light-9);
}

.ip-stat-item {
  transition: all 0.2s ease;
}

.ip-stat-item:hover {
  background: var(--el-color-primary-light-9);
}

.permission-stat {
  padding: 1rem;
  background: var(--el-bg-color-page);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);
}

.progress-bar {
  background: var(--el-color-info-light-8);
}

.progress-fill {
  transition: width 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-actions-area {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .page-actions-area button {
    width: 100%;
    justify-content: center;
  }
}
</style>
